#include "TcpServer.h"
#include "Logger.h"
#include "TcpConnection.h"

#include <strings.h>
#include <functional>

EventLoop* TcpServer::CheckLoopNotNull(EventLoop* loop)
{
    if(loop==nullptr)
    {
        LOG_FATAL("%s:%s:%d mainloop is null \n",__FILE__,__FUNCTION__,__LINE__);
    }
    return loop;
}

TcpServer::TcpServer(EventLoop* loop,const InetAddress& listenAddr,const std::string& name,Option option)
    : loop_(CheckLoopNotNull(loop))
    , ipPort_(listenAddr.toIpPort())
    , name_(name)
    , acceptor_(new Acceptor(loop,listenAddr,option==kReusePort))
    , threadPool_(new EventLoopThreadPool(loop,name_))
    , connectionCallback_()
    , messageCallback_()
    , nextConnId_(1)
    , started_(0)
{
    // 当有新用户连接时 执行newConnection回调
    acceptor_->setNewConnectionCallback(std::bind(&TcpServer::newConnection,this,std::placeholders::_1,std::placeholders::_2));

}

TcpServer::~TcpServer()
{
    // 遍历所有存储TcpConnectionPtr的容器
    for(auto& it :connections_)
    {
        // 增加智能指针的引用计数（确保conn在作用域内不被销毁）
        TcpConnectionPtr conn(it.second);
        // 重置容器中的智能指针（引用计数减1，此时仅conn持有该连接
        it.second.reset();

        // conn->getLoop()：获取该 TcpConnection 所属的 EventLoop
        // runInLoop(...)：将任务（TcpConnection::connectDestroyed）提交到连接所属的 EventLoop 中执行
        // std::bind(&TcpConnection::connectDestroyed, conn)：绑定销毁函数，conn 作为参数传递
        conn->getLoop()->runInLoop(std::bind(&TcpConnection::connectDestroyed,conn));

    }
}

void TcpServer::newConnection(int sockfd,const InetAddress& peerAddr)
{
    EventLoop* ioLoop =threadPool_->getNextLoop();
    char buf[64]={0};
    snprintf(buf,sizeof buf,"-%s#%d",ipPort_.c_str(),nextConnId_++);
    std::string connName = name_ +buf;

    LOG_INFO("TcpServer::newConnection [%s] - new connection [%s] from %s \n",name_.c_str(),connName.c_str(),peerAddr.toIpPort().c_str());

    sockaddr_in local;
    ::bzero(&local,sizeof local);
    socklen_t addrlen =sizeof local;
    if(::getsockname(sockfd,(sockaddr*)&local,&addrlen)>0)
    {
        LOG_ERROR("sockets::getLocalAddr \n");
    }

    InetAddress localAddr(local);

    TcpConnectionPtr conn(new TcpConnection(ioLoop,connName,sockfd,localAddr,peerAddr));
    connections_[connName]=conn;
    // 下面的回调 为用户设置
    conn->setConnectionCallback(connectionCallback_);
    conn->setMessageCallback(messageCallback_);
    conn->setWriteCompleteCallback(writeCompleteCallback_);
    conn->setCloseCallback(std::bind(&TcpServer::removeConnection,this,std::placeholders::_1));
    ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished,conn));
}
void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
    loop_->runInLoop(std::bind(&TcpServer::removeConnectionInLoop,this,conn));
}
void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
    LOG_INFO("TcpServer::removeConnectionInLoop [%s] -connection %s \n",name_.c_str(),conn->name().c_str());
    connections_.erase(conn->name());
    EventLoop* ioLoop = conn->getLoop();
    ioLoop->queueInLoop(std::bind(&TcpConnection::connectDestroyed,conn));

}



void TcpServer::setThreadNum(int numThreads)
{
    threadPool_->setThreadNumber(numThreads);
}

void TcpServer::start()
{
    if(started_++ == 0) // 防止一个TcpServer对象被start多次
    {
        threadPool_->start(threadInitCallback_);
        loop_->runInLoop(std::bind(&Acceptor::listen,acceptor_.get())); 
    }
}
